package com.itxh.core.builder;

import com.itxh.core.config.Configuration;
import com.itxh.core.config.MappedStatement;
import com.itxh.core.sqlsource.SqlSource;
import org.dom4j.Element;

public class XMLStatementBuilder {
    private Configuration configuration;

    public XMLStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseStatement(String namespace, Element selectElement) {
        String statementId = selectElement.attributeValue("id");
        if (statementId == null || statementId.equals("")){
            return;
        }
        statementId = namespace + "." + statementId;
        String parameterType = selectElement.attributeValue("parameterType");
        String resultType = selectElement.attributeValue("resultType");
        if (resultType == null || resultType.equals("")){
            return;
        }
        String statementType = selectElement.attributeValue("statementType");
        statementType = statementType == null || statementType.equals("")?"prepared":statementType;

        SqlSource sqlSource = createSqlSource(selectElement);

        MappedStatement mappedStatement = new MappedStatement(statementId,parameterType,resultType,statementType,sqlSource);
        configuration.addMappedStatement(statementId,mappedStatement);
    }

    private SqlSource createSqlSource(Element selectElement) {
        XMLScriptBuilder scriptBuilder = new XMLScriptBuilder();
        return scriptBuilder.parseScriptNode(selectElement);
    }
}
